import DatePicker from "components/antd-compatible/date-picker";
import React, { Component } from "react";
import { connect } from 'react-redux'
import { Form, Input, Button, message,  Select, Spin, Row, Col, InputNumber } from 'antd'
import { messages } from "share/common"
import moment from 'moment'
import borrowService from "../../../loan-billing/borrow-and-return.service"

const { Option } = Select;

@connect(mapStateToProps)
@Form.create()
class EditAudit extends Component{

  state = {
    saveLoading: false,
    selectLoading: false,
    accountOption: [],
    paymentOption: [],
    paymentLoading: false,
    allInfo: {}
  };

  componentDidMount = () => {
    this.getBank();
    this.getPayment()
  };

  getPayment = () => {
    this.setState({ paymentLoading: true });
    borrowService.getAllPaymentType().then(res => {
      this.setState({ paymentOption: res.data });
    }).catch(e => {
      message.error(e.response.data.message)
    }).finally(() => {
      this.setState({ paymentLoading: false })
    })
  };

  getBank = () => {
    const { record, info } = this.props.params;
    this.setState({ selectLoading: true });
    borrowService.getLineDetail(record.id, true).then(res => {
      this.setState({ allInfo: res.data }, () => {
        if (record.payeeType === 1002) {
          borrowService.getUserCompanyAccount(res.data.payeeOid).then(response => {
            this.setState({
              accountOption: response.data,
              selectLoading: false
            })
          })
        } else {
          borrowService.getVendorAccount(info.companyOID, info.companyId, record.payeeName).then(response => {
            response.data.map(vendorItem => {
              if (vendorItem.id === res.data.payeeId) {
                this.setState({
                  accountOption: vendorItem.venBankAccountBeans,
                  selectLoading: false
                })
              }
            })
          })
        }
      });
    }).catch(e => {
      message.error(e.response.data.message)
    })
  };

  handleSave = () => {
    this.props.form.validateFieldsAndScroll((err, value) => {
      if (!err) {
        const { method, methodParams, listKey } = this.props.params, { close } = this.props;
        this.setState({ saveLoading: true });
        let params = methodParams;
        if (listKey) {
          params[listKey] = Object.assign(params[listKey], value);
        } else {
          params = Object.assign(params, value);
        }
        method(params).then(() => {
          this.setState({ saveLoading: false });
          close(true);
        }).catch(e => {
          this.setState({ saveLoading: false });
          message.error(e.response.data.message);
        })
      }
    });
  };

  changeBankAccount = value => {
    const { record, formInfo } = this.props.params, { accountOption } = this.state;
    const { payeeType } = record;
    let temp = null;
    accountOption.map(item => {
      payeeType === 1002 && item.bankAccountNo === value && (temp = item);
      payeeType === 1001 && item.bankAccount === value && (temp = item);
    });
    let fieldValue = {
      payeeAccountName: payeeType === 1002 ? temp.bankAccountName : temp.venBankNumberName,
      paymentType: ((payeeType === 1002 && temp.sourceType === 'ALIPAY_LOGON_ID') || temp.accountType === 'ALIPAY_LOGON_ID')
        ? 'ONLINE_PAYMENT'
        : formInfo.customFormPropertyMap['loan.bill.pay.type']
    };
    fieldValue.paymentType !== this.props.form.getFieldValue('paymentType') && (fieldValue.paymentMethodId = undefined);
    this.props.form.setFieldsValue(fieldValue)
  };

  handlePaymentNameChange = value => {
    const { paymentOption } = this.state;
    this.props.form.setFieldsValue({
      paymentType: paymentOption.find(item => item.id === value).paymentMethodCategory
    });
  };

  render() {
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 10 },
      },
    };
    const { saveLoading, selectLoading, accountOption, paymentOption, paymentLoading, allInfo } = this.state;
    const { getFieldDecorator } = this.props.form;
    const { close, options } = this.props;
    const { record, remarkIsRequired = true, formInfo } = this.props.params;
    const { payeeType } = record;
    let isNeedContract = formInfo.customFormPropertyMap && formInfo.customFormPropertyMap['loan.property.associated.contract.enabled'] === 'true';
    return (
      <div>
        <Form className={'new-form'}>
          <Row style={{marginBottom: '0'}}>
            <div className="form-define-title required ant-form-item-label">{messages('finance-1.key16')/*借款金额*/}：</div>
            <Col span={3}>
              <Input disabled value={record.currencyCode}/>
            </Col>
            <Col span={10} offset={1}>
              <Form.Item>
                {getFieldDecorator('amount', {
                  rules: [{
                    validator: (rule, value, callback) => {
                      if (value === null || value === undefined || value === "") {
                        callback(messages('common.please.input')/*请输入*/);
                        return;
                      }
                      let reg = new RegExp('^([0-9])*((\\.)([0-9])+){0,1}$','g');
                      if(reg.test(value)){
                        callback();
                      }else{
                        callback(messages('finance-1.key149')/*请输入正数*/);
                      }
                    }
                  }],
                  initialValue: record.amount
                })(
                  <InputNumber
                    min={0}
                    max={record.amount}
                    precision={2}
                    disabled={!options.auditBaseConfig.loanAmountAlter}
                    style={{width: '100%'}}
                    placeholder={messages('finance-1.key76')/*请输入*/}
                  />
                )}
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            label={messages('expense-14.key156')/*备注*/}
            {...formItemLayout}
          >
            {getFieldDecorator('remark', {
              rules: [{
                required: remarkIsRequired,
                message: messages('common.please.input')/*请输入*/
              }, {
                max: 500,
                message: messages('common.max.characters.length',{arg1: 500})/*最多输入{arg1}个字符*/
              }],
              initialValue: record.remark
            })(
              <Input.TextArea
                placeholder={messages('common.max.characters.length',{arg1: 500})/*最多输入{arg1}个字符*/}
                rows={3}
                style={{resize: 'none'}}
              />
            )}
          </Form.Item>
          {
            isNeedContract && (
              <Form.Item
                label={messages('finance-1.key55')/*计划付款日期*/}
                {...formItemLayout}
              >
                {getFieldDecorator('planedPaymentDate', {
                  initialValue: record.planedPaymentDate ? moment(moment(record.planedPaymentDate).local(),'YYYY-MM-DD') :
                    moment(moment(new Date()),'YYYY-MM-DD')
                })(
                  <DatePicker format="YYYY-MM-DD" placeholder={messages('common.select')/*请选择*/}/>
                )}
              </Form.Item>
            )
          }
          <Form.Item
            label={messages('finance-1.key146')/*收款方账户*/}
            {...formItemLayout}
          >
            {getFieldDecorator('payeeAccountNumber', {
              rules: [{ required: options.loanOption.option1 === 'true', message: messages('common.select')/*请选择*/ }],
              initialValue: record.payeeAccountNumber
            })(
              <Select
                notFoundContent={selectLoading ? <Spin size="small"/> : messages('common.unmatched')/*无匹配结果*/}
                onChange={this.changeBankAccount}
                placeholder={messages('common.select')/*请选择*/}
              >
                {
                  accountOption.map(item => (
                    <Option
                      key={payeeType === 1002 ? item.bankAccountNo : item.bankAccount}
                      title={payeeType === 1002 ? item.bankAccountNo : item.bankAccount}
                      style={{whiteSpace: 'normal'}}
                    >
                      {payeeType === 1002 ? item.bankAccountNo : item.bankAccount} {item.branchName || item.bankName}
                      {item.notes ? `(${item.notes})` : ''}
                    </Option>
                  ))
                }
              </Select>
            )}
          </Form.Item>
          <Form.Item
            label={messages('finance-1.key147')/*收款方户名*/}
            {...formItemLayout}
          >
            {getFieldDecorator('payeeAccountName', {
              initialValue: record.payeeAccountName
            })(
              <Input disabled placeholder={messages('finance-1.key76')/*请输入*/}/>
            )}
          </Form.Item>
          <Form.Item
            label={messages('finance-1.key26')/*付款方式类型*/}
            {...formItemLayout}
          >
            {getFieldDecorator('paymentType', {
              rules: [{
                required: true,
                message: messages('common.select')/*请选择*/
              }],
              initialValue: record.paymentType
            })(
              <Select disabled placeholder={messages('common.select')/*请选择*/}>
                <Option key={'ONLINE_PAYMENT'}>{messages('finance-1.key116')/*线上*/}</Option>
                <Option key={'OFFLINE_PAYMENT'}>{messages('finance-1.key117')/*线下*/}</Option>
                <Option key={'EBANK_PAYMENT'}>{messages('finance-1.key118')/*落地文件*/}</Option>
              </Select>
            )}
          </Form.Item>
          {
            formInfo.customFormPropertyMap && formInfo.customFormPropertyMap['loan.bill.pay.method.changeable'] === 'true' && (
              <Form.Item
                label={messages('expense-14.key515')/*付款方式*/}
                {...formItemLayout}
              >
                {getFieldDecorator('paymentMethodId', {
                  rules: [{
                    required: true,
                    message: messages('common.select')/*请选择*/
                  }],
                  initialValue: allInfo.paymentMethodId
                })(
                  <Select
                    notFoundContent={paymentLoading ? <Spin size="small"/> : messages('common.unmatched')/*无匹配结果*/}
                    placeholder={messages('common.select')/*请选择*/}
                    onChange={this.handlePaymentNameChange}
                  >
                    {paymentOption.map(item => <Option key={item.id}>{item.description}</Option>)}
                  </Select>
                )}
              </Form.Item>
            )
          }
        </Form>
        <div className='slide-footer'>
          <Button type='primary' onClick={this.handleSave} loading={saveLoading}>{messages('common.save')/*保存*/}</Button>
          <Button onClick={() => close()}>{messages('common.cancel')/*取消*/}</Button>
        </div>
      </div>
    )
  }

}

function mapStateToProps(state){
  return {
    options: state.login.options
  }
}

export default EditAudit
